//
//  CQCycleView.m
//  轮播图封装(CollectionView版本)
//
//  Created by CoderDoctorLee on 16/5/26.
//  Copyright © 2016年 CoderDoctorLee. All rights reserved.
//

#import "CQCycleView.h"
#import "CQCycleViewCell.h"
#import "UIImageView+WebCache.h"
#import "MPageControl.h"
#define SECTION_COUNT 1000
#define WIDTHOFMAIN [UIScreen mainScreen].bounds.size.width
#define HEIGHTOFMAIN [UIScreen mainScreen].bounds.size.height
@interface CQCycleView ()<UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate>
/** 轮播图控件 */
@property(nonatomic, strong)UICollectionView *collectionView;
/** 数据源数组 */
@property(nonatomic, strong)NSArray *dataSourceArray;
/** 定时器时间间隔 */
@property(nonatomic, assign)CGFloat timeInterval;
/** 定时器对象 */
@property(nonatomic, strong)NSTimer *cycleTimer;
/** 当前item的下标 */
@property(nonatomic, assign)NSInteger itemIndex;
/** 当前section下标 */
@property(nonatomic, assign)NSInteger currentSection;

@property(nonatomic, strong)MPageControl *pageControl;
@property(nonatomic, strong)NSMutableArray *imageArray;
@end


@implementation CQCycleView

- (instancetype)initWithFrame:(CGRect)frame DataSource:(NSArray *)dataSource TimeInterval:(CGFloat)time
{
    
    self = [super initWithFrame:frame];
    
    _imageArray = [NSMutableArray array];
      

    
    if (self) {
        
            //将外界传递进来的数据源赋值给dataSourceArray:
            self.dataSourceArray = dataSource;
            //初始化默认瀑布流样式:
            UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
            flowLayout.itemSize = frame.size;
            flowLayout.minimumInteritemSpacing = 0;
            flowLayout.minimumLineSpacing = 0;
            flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
            flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            //初始化collectionView:
            self.collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
            self.collectionView.backgroundColor = [UIColor whiteColor];
            self.collectionView.dataSource = self;
            self.collectionView.delegate = self;
            self.collectionView.pagingEnabled = YES;
            self.collectionView.showsHorizontalScrollIndicator = NO;
            [self addSubview:_collectionView];
        
        
        _pageControl = [[MPageControl alloc]initWithFrame:CGRectMake(0, HEIGHTOFMAIN / 3.5, WIDTHOFMAIN, HEIGHTOFMAIN / 3- HEIGHTOFMAIN / 3.5) pageStyle:XMHPageControlStyleSquare withImageArray:_imageArray];
        
        _pageControl.selectedColor = [UIColor grayColor];
        _pageControl.pageBackgroundColor = [UIColor whiteColor];
       // _pageControl.pageNumber = 5;
        
        _pageControl.currentPageNumber = 0;
        [self addSubview:_pageControl];
      
            //注册cell:
            [self.collectionView registerClass:[CQCycleViewCell class] forCellWithReuseIdentifier:@"LM_Cell"];
            //设置初始偏移量:(适用于非网络请求的图片，不需要刷新)
            if (self.dataSourceArray.count > 1) {
                [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
            }
            //判断时间是否合理!
            if (time > 0) {
                self.timeInterval = time;
                [self addTimer];//开启定时器
            }
    }
    return self;
}

#pragma mark -- item的个数:
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    
    return self.dataSourceArray.count;
}
#pragma mark -- section的个数:
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return SECTION_COUNT;
}
#pragma mark -- 为item赋值:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.dataSourceArray.count != 0) {
        CQCycleViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"LM_Cell" forIndexPath:indexPath];
        _pageControl.currentPageNumber = indexPath.item;
        

        //记录当前的item和section:
        //NSLog(@"%ld --- %ld", indexPath.section, _itemIndex);
        if (indexPath.item > _itemIndex)
        {
            _itemIndex = indexPath.item;
        }

        _currentSection = indexPath.section;
    // NSLog(@"section : %ld", _currentSection);
        //加一个数据保护
        if (self.dataSourceArray.count != 0) {
            [cell.cycleImageView sd_setImageWithURL:[NSURL URLWithString:[self.dataSourceArray objectAtIndex:indexPath.item]]];
        }
        //添加循环保护:(防止到最后一个分区出现崩溃)
        if (indexPath.section == SECTION_COUNT - 1) {
            //回到最初的起点
            [collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
        }
        return cell;
    }
    return [UICollectionViewCell new];
}

#pragma mark -- 点击item触发的方法:
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    NSLog(@"点击了图片:%ld", indexPath.item);
    //命令代理人去执行代理方法:
    if (self.delegate != nil) {
        [self.delegate didClickedItemAtIndexPath:indexPath];
    }
}

#pragma mark -- 添加定时器:
- (void)addTimer
{
    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:self.timeInterval target:self selector:@selector(changePageByTime) userInfo:nil repeats:YES];
    [[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    self.cycleTimer = timer;
}
#pragma mark -- 移除定时器:
- (void)removeTimer
{
    [self.cycleTimer invalidate];
    self.cycleTimer = nil;
}

#pragma mark -- 定时器调用的方法:
- (void)changePageByTime
{
    if (_itemIndex == self.dataSourceArray.count) {
        _itemIndex = 0;
        _currentSection++;
    }
    if (self.dataSourceArray.count > 0) {
        //偏移到最新位置(下一张)
        [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_itemIndex inSection:_currentSection] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        _itemIndex++;
    }
}

#pragma mark -- 手指开始滑动时定时器失效:
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (_timeInterval > 0) {
        [self removeTimer];
    }
}
#pragma mark -- 手指离开定时器开启:
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_timeInterval > 0) {
        [self addTimer];
    }
}

#pragma mark -- 刷新
- (void)reloadDataByArray:(NSMutableArray *)dataSource
{
    
    self.dataSourceArray = dataSource;
    [self.collectionView reloadData];
    [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:0 inSection:SECTION_COUNT / 2] atScrollPosition:UICollectionViewScrollPositionLeft animated:NO];
}


-(void)number:(NSUInteger *)number{
    
    _pageControl.pageNumber = number;

    
}

@end





